package cup.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cup.common.cache.SysCache;
import cup.core.secure.CupUser;
import cup.core.tool.utils.BeanUtil;
import cup.core.tool.utils.CollectionUtil;
import cup.modules.system.entity.Dept;
import cup.modules.system.vo.DeptVO;
import cup.modules.system.wrapper.DeptWrapper;
import cup.core.log.exception.ServiceException;
import cup.core.secure.utils.AuthUtil;
import cup.core.tool.constant.CupConstant;
import cup.core.tool.node.ForestNodeMerger;
import cup.core.tool.utils.Func;
import cup.core.tool.utils.StringPool;
import cup.modules.system.mapper.DeptMapper;
import cup.modules.system.service.IDeptService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {
	private static final String TENANT_ID = "tenantId";
	private static final String PARENT_ID = "parentId";

	private final DeptMapper deptMapper;

	@Autowired
	public DeptServiceImpl(DeptMapper deptMapper) {
		this.deptMapper = deptMapper;
	}

	@Override
	public List<DeptVO> lazyContactList(String tenantId, Long parentId, Map<String, Object> param) {
		// 设置租户ID
		if (AuthUtil.isAdministrator()) {
			tenantId = StringPool.EMPTY;
		}
		String paramTenantId = Func.toStr(param.get(TENANT_ID));
		if (Func.isNotEmpty(paramTenantId) && AuthUtil.isAdministrator()) {
			tenantId = paramTenantId;
		}
		// 判断点击搜索但是没有查询条件的情况
		if (Func.isEmpty(param.get(PARENT_ID)) && param.size() == 1) {
			parentId = 0L;
		}
		// 判断点击搜索带有查询条件的情况
		if (Func.isEmpty(param.get(PARENT_ID)) && param.size() > 1 && Func.toLong(parentId) == 0L) {
			parentId = null;
		}
		return baseMapper.lazyList(tenantId, parentId, param);
	}

	@Override
	public Dept currentParent() {
		CupUser cupUser = Optional.ofNullable(AuthUtil.getUser()).orElseThrow(() -> new ServiceException("请先登录"));
		List<Dept> deptList = this.baseMapper.selectList(null);
		Long parentId = getParentDeptId(Long.valueOf(cupUser.getDeptId()), deptList);
		return this.baseMapper.selectOne(new LambdaQueryWrapper<Dept>().eq(Dept::getId, parentId).eq(Dept::getIsDeleted, 0));
	}

	private Long getParentDeptId(Long deptId, List<Dept> deptList) {
		Dept current = deptList.stream().filter(d -> deptId.equals(d.getId())).findFirst().orElseThrow(() -> new ServiceException("数据不存在"));
		if (Integer.valueOf(3).equals(current.getDeptCategory())) {
			return getParentDeptId(current.getParentId(), deptList);
		}
		return current.getId();
	}

	@Override
	public List<DeptVO> lazyList(String tenantId, Long parentId, Map<String, Object> param) {
		// 设置租户ID
		if (AuthUtil.isAdministrator()) {
			tenantId = StringPool.EMPTY;
		}
		String paramTenantId = Func.toStr(param.get(TENANT_ID));
		if (Func.isNotEmpty(paramTenantId) && AuthUtil.isAdministrator()) {
			tenantId = paramTenantId;
		}
		// 判断点击搜索但是没有查询条件的情况
		if (Func.isEmpty(param.get(PARENT_ID)) && param.size() == 1) {
			parentId = 0L;
		}
		// 判断数据权限控制,非超管角色只可看到本级及以下数据
		if (Func.toLong(parentId) == 0L && !AuthUtil.isAdministrator()) {
			Long deptId = Func.firstLong(AuthUtil.getDeptId());
			Dept dept = SysCache.getDept(deptId);
			if (dept.getParentId() != 0) {
				parentId = dept.getParentId();
			}
		}
		// 判断点击搜索带有查询条件的情况
		if (Func.isEmpty(param.get(PARENT_ID)) && param.size() > 1 && Func.toLong(parentId) == 0L) {
			parentId = null;
		}
		return baseMapper.lazyList(tenantId, parentId, param);
	}

	@Override
	public List<DeptVO> tree(String tenantId) {
		return ForestNodeMerger.merge(baseMapper.tree(tenantId));
	}

	@Override
	public List<DeptVO> lazyTree(String tenantId, Long parentId) {
		if (AuthUtil.isAdministrator()) {
			tenantId = StringPool.EMPTY;
		}
		return ForestNodeMerger.merge(baseMapper.lazyTree(tenantId, parentId));
	}

	@Override
	public String getDeptIds(String tenantId, String deptNames) {
		List<Dept> deptList = baseMapper.selectList(Wrappers.<Dept>query().lambda().eq(Dept::getTenantId, tenantId).in(Dept::getDeptName, Func.toStrList(deptNames)));
		if (deptList != null && deptList.size() > 0) {
			return deptList.stream().map(dept -> Func.toStr(dept.getId())).distinct().collect(Collectors.joining(","));
		}
		return null;
	}

	@Override
	public String getDeptIdsByFuzzy(String tenantId, String deptNames) {
		LambdaQueryWrapper<Dept> queryWrapper = Wrappers.<Dept>query().lambda().eq(Dept::getTenantId, tenantId);
		queryWrapper.and(wrapper -> {
			List<String> names = Func.toStrList(deptNames);
			names.forEach(name -> wrapper.like(Dept::getDeptName, name).or());
		});
		List<Dept> deptList = baseMapper.selectList(queryWrapper);
		if (deptList != null && deptList.size() > 0) {
			return deptList.stream().map(dept -> Func.toStr(dept.getId())).distinct().collect(Collectors.joining(","));
		}
		return null;
	}

	@Override
	public List<String> getDeptNames(String deptIds) {
		return baseMapper.getDeptNames(Func.toLongArray(deptIds));
	}

	@Override
	public List<Dept> getDeptChild(Long deptId) {
		return baseMapper.selectList(Wrappers.<Dept>query().lambda().like(Dept::getAncestors, deptId));
	}

	@Override
	public boolean removeDept(String ids) {
		Integer cnt = baseMapper.selectCount(Wrappers.<Dept>query().lambda().in(Dept::getParentId, Func.toLongList(ids)));
		if (cnt > 0) {
			throw new ServiceException("请先删除子节点!");
		}
		return removeByIds(Func.toLongList(ids));
	}

	@Override
	public boolean submit(Dept dept) {
		if (Func.isEmpty(dept.getParentId())) {
			dept.setTenantId(AuthUtil.getTenantId());
			dept.setParentId(CupConstant.TOP_PARENT_ID);
			dept.setAncestors(String.valueOf(CupConstant.TOP_PARENT_ID));
		}
		if (dept.getParentId() > 0) {
			Dept parent = getById(dept.getParentId());
			if (Func.toLong(dept.getParentId()) == Func.toLong(dept.getId())) {
				throw new ServiceException("父节点不可选择自身!");
			}
			dept.setTenantId(parent.getTenantId());
			String ancestors = parent.getAncestors() + StringPool.COMMA + dept.getParentId();
			dept.setAncestors(ancestors);
		}
		dept.setIsDeleted(CupConstant.DB_NOT_DELETED);
		return saveOrUpdate(dept);
	}

	@Override
	public List<DeptVO> search(String deptName, Long parentId) {
		LambdaQueryWrapper<Dept> queryWrapper = Wrappers.<Dept>query().lambda();
		if (Func.isNotEmpty(deptName)) {
			queryWrapper.like(Dept::getDeptName, deptName);
		}
		if (Func.isNotEmpty(parentId) && parentId > 0L) {
			queryWrapper.eq(Dept::getParentId, parentId);
		}
		List<Dept> deptList = baseMapper.selectList(queryWrapper);
		return DeptWrapper.build().listNodeVO(deptList);
	}

	public List<Dept> currentDeptOnly() {
		CupUser user = AuthUtil.getUser();
		List<Dept> depts = this.baseMapper.selectList(new LambdaQueryWrapper<Dept>().eq(Dept::getTenantId, user.getTenantId()));
		Long parentDeptId = getParentDeptId(Long.valueOf(user.getDeptId()), depts);
		List<Dept> deptList = gather(parentDeptId);
		return deptList.stream().filter(item -> item.getParentId().equals(parentDeptId)).filter(item -> item.getDeptCategory() == 3).collect(Collectors.toList());
	}

	@Override
	public List<Dept> gather(Long parentId) {
		List<Dept> depts = new ArrayList<>();
//		Dept dept = Optional.ofNullable(this.baseMapper.selectOne(new LambdaQueryWrapper<Dept>().eq(Dept::getId, parentId).eq(Dept::getIsDeleted, CupConstant.DB_NOT_DELETED))).orElseThrow(() -> new ServiceException("该数据不存在"));
//		depts.add(dept);
//		List<Dept> deptList = this.baseMapper.selectList(new LambdaQueryWrapper<Dept>().eq(Dept::getIsDeleted, CupConstant.DB_NOT_DELETED).eq(Dept::getTenantId, user.getTenantId()));
		//添加子集
		DeptVO deptVO = this.selfAndDetails(parentId);
		gatherDept(depts, deptVO);

		//添加自身
		Dept dept = new Dept();
		BeanUtil.copyProperties(deptVO, dept);
		depts.add(0, dept);
		return depts;
	}

	@Override
	public DeptVO selfAndDetails(Long parentId) {
		CupUser user = AuthUtil.getUser();
		Dept dept = Optional.ofNullable(this.baseMapper.selectOne(new LambdaQueryWrapper<Dept>().eq(Dept::getId, parentId).eq(Dept::getIsDeleted, CupConstant.DB_NOT_DELETED))).orElseThrow(() -> new ServiceException("该数据不存在"));
		DeptVO self = new DeptVO();
		BeanUtil.copyProperties(dept, self);
		List<Dept> depts = this.baseMapper.selectList(new LambdaQueryWrapper<Dept>().eq(Dept::getIsDeleted, CupConstant.DB_NOT_DELETED).eq(Dept::getTenantId, user.getTenantId()));
		List<DeptVO> deptVOS = CollectionUtil.isNotEmpty(depts) ? depts.parallelStream().map(d -> toVo(d)).collect(Collectors.toList()) : new ArrayList<>();
		buildDetails(self, deptVOS);
		return self;
	}

	private void gatherDept(List<Dept> depts, DeptVO deptVO) {
/*		if (CollectionUtil.isNotEmpty(deptVO.getChildren())) {
			deptVO.getChildren().parallelStream().map(d -> {
				Dept dept = new Dept();
				BeanUtil.copyProperties(d, dept);
				depts.add(dept);
				gatherDept(depts, d);
				return dept;
			}).collect(Collectors.toList());
		}*/
		List<DeptVO> children = deptVO.getChildren();
		if (CollUtil.isNotEmpty(children)) {
			for (DeptVO child : children) {
				Dept dept = new Dept();
				BeanUtil.copyProperties(child, dept);
				depts.add(dept);
				gatherDept(depts, child);
			}
		}
	}

	private void buildDetails(DeptVO parent, List<DeptVO> deptVOS) {
		List<DeptVO> children = deptVOS.parallelStream().filter(d -> d.getParentId().equals(parent.getId())).map(d -> {
			buildDetails(d, deptVOS);
			d.setParentName(parent.getDeptName());
			d.setDeptCategoryName(parent.getDeptCategoryName());
			return d;
		}).collect(Collectors.toList());
		parent.setChildren(children);
		parent.setHasChildren(!CollectionUtil.isEmpty(children));
	}

	private DeptVO toVo(Dept dept) {
		DeptVO deptVO = new DeptVO();
		BeanUtils.copyProperties(dept, deptVO);
		return deptVO;
	}

	@Override
	public List<Dept> subDeptsOnly(Long companyId) {

		List<Dept> deptList = this.baseMapper.selectList(null);
		DeptVO deptVO = toVo(deptList.stream().filter(item -> item.getId().equals(companyId)).findFirst().get());
		buildDetails(deptVO, toVoList(deptList));
		List<Dept> depts = new ArrayList<>();
		gatherDept(depts, deptVO);
		return depts;
	}

	public List<DeptVO> toVoList(List<Dept> depts) {
		return depts.stream().map(item -> toVo(item)).collect(Collectors.toList());
	}


	@Override
	public List<String> findDeptAndChild(String deptId) {
		return deptMapper.findDeptAndChild(deptId);
	}

	@Override
	public Dept getParentInfoById(String regionCode) {
		return deptMapper.getParentInfoById(regionCode);
	}

	@Override
	public DeptVO schedule() {
		Dept parent = this.currentParent();
		CupUser user = AuthUtil.getUser();
		List<DeptVO> deptVOS = this.baseMapper.selectList(new LambdaQueryWrapper<Dept>().eq(Dept::getTenantId, user.getTenantId()))
			.stream().map(item -> toVo(item)).collect(Collectors.toList());
		//政府侧 返回当前部门及子部门
		if (ObjectUtil.equal(4, parent.getDeptCategory())) {
			DeptVO dept = toVo(this.baseMapper.selectById(AuthUtil.getUser().getDeptId()));
			buildDetails(dept, deptVOS);
			return dept;
		}
		//企业侧 返回父级别
		return toVo(parent);
	}


	@Override
	public List<DeptVO> dutyTree(String deptId) {
		return ForestNodeMerger.merge(baseMapper.dutyTree(deptId));
	}
}
